package httpserver

import (
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/AjaxResult"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

type server struct {
	engine *gin.Engine
	router map[string]interface{}
}

func (e *server) GET(path string, handler HandlerGet) {
	e.engine.GET(path, func(context *gin.Context) {
		data, err := handler(context)
		e.respond(context, data, err)
	})

	e.router[path+":"+"GET"] = handler
}

func (e *server) DELETE(path string, handler HandlerDel) {
	e.engine.DELETE(path, func(context *gin.Context) {
		data, err := handler(context)
		e.respond(context, data, err)
	})

	e.router[path+":"+"DELETE"] = handler
}

func (e *server) POST(path string, handler HandlerPost) {
	e.engine.POST(path, func(context *gin.Context) {
		body := make(map[string]interface{})
		err := context.ShouldBindJSON(&body)
		if err != nil {
			e.respond(context, nil, err)
			return
		}

		data, err := handler(context, body)
		e.respond(context, data, err)
	})

	e.router[path+":"+"POST"] = handler
}

func (e *server) POSTRaw(path string, handler HandlerPost) {
	e.engine.POST(path, func(context *gin.Context) {
		body := make(map[string]interface{})
		err := context.ShouldBindJSON(&body)
		if err != nil {
			e.respond(context, nil, err)
			return
		}

		data, err := handler(context, body)
		if err != nil {
			e.respond(context, nil, err)
			return
		}
		context.JSON(http.StatusOK, data)
	})

	e.router[path+":"+"POST"] = handler
}

func (e *server) PUT(path string, handler HandlerPut) {
	e.engine.PUT(path, func(context *gin.Context) {
		body := make(map[string]interface{})
		err := context.ShouldBindJSON(&body)
		if err != nil {
			e.respond(context, nil, err)
			return
		}

		data, err := handler(context, body)
		e.respond(context, data, err)
	})

	e.router[path+":"+"PUT"] = handler
}

func (e *server) respond(context *gin.Context, data interface{}, err error) {
	if err != nil {
		context.JSON(http.StatusOK, AjaxResult.Error(err.Error(), nil))
	} else {
		context.JSON(http.StatusOK, AjaxResult.Success("操作成功", data))
	}
}

func (e *server) startServer() {
	// 启动服务
	serverPort := fmt.Sprintf(":%v", commEnv.Service.AppPort)
	if err := e.engine.Run(serverPort); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
